const connection = require('../app/database');

class CommentService {

  // 创建一条评论
  async create(content, momentId, userId) {
    try {
      const statement = `INSERT INTO comment (content, moment_id, user_id) VALUES (?, ?, ?)`;
      const result = await connection.execute(statement, [content, momentId, userId]);
      return result[0];
    } catch (error) {
      console.log(error);
    }
  }

  // 回复一条评论
  async reply(content, momentId, commentId, userId) {
    try {
      const statement = `INSERT INTO comment (content, moment_id, user_id, comment_id) VALUES (?, ?, ?, ?)`;
      const result = await connection.execute(statement, [content, momentId, userId, commentId]);
      return result[0];
    } catch (error) {
      console.log(error);
    }
  }

  // 删除一条评论
  async remove(userId, commentId) {
    try {
      const statement = `DELETE FROM comment WHERE user_id = ? AND id = ?`;
      const result = await connection.execute(statement, [userId, commentId]);
      return result[0];
    } catch (error) {
      console.log(error);
    }
  }

  // 获取评论列表
  async getCommentList(momentId, offset, limit) {
    try {
      const statement = `SELECT 
                            c.id id, 
                            c.content content, 
                            c.likes likes,
                            c.moment_id momentId,
                            c.comment_id commentId,
                            c.createAt createTime, 
                            c.updateAt updateTime,
                          JSON_OBJECT('id', u.id, 'nickname', u.nickname, 'avatarUrl', u.avatar_url, 'isPrivate', u.private) user
                          FROM comment c
                          LEFT JOIN user u ON u.id = c.user_id
                          WHERE c.moment_id = ?
                          LIMIT ?, ?`;
      const result = await connection.execute(statement, [momentId, offset, limit]);
      return result[0];
    } catch (error) {
      console.log(error);
    }
  }

}

module.exports = new CommentService();
